package com.example.testapp.ui.balance

import android.app.Application
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.viewModelScope
import com.example.testapp.data.AppDatabase
import com.example.testapp.data.entity.Balance
import com.example.testapp.data.entity.BalanceImage
import com.example.testapp.data.entity.BalanceProcessRecord
import com.example.testapp.data.repository.BalanceRepository
import kotlinx.coroutines.launch
import java.io.File
import java.time.LocalDateTime

/**
 * 账单ViewModel，负责管理UI相关数据
 */
class BalanceViewModel(application: Application) : AndroidViewModel(application) {

    private val repository: BalanceRepository
    val allBalances: LiveData<List<Balance>>
    private val _selectedBalanceId = MutableLiveData<Long>()
    private val _operationState = MutableLiveData<OperationState>()
    
    val operationState: LiveData<OperationState> = _operationState
    private val _selectedBalance = MediatorLiveData<Balance?>()
    val selectedBalance: LiveData<Balance?> = _selectedBalance
    
    private val _balanceImages = MediatorLiveData<List<BalanceImage>>()
    val balanceImages: LiveData<List<BalanceImage>> = _balanceImages
    
    private val _processingRecords = MutableLiveData<List<BalanceProcessRecord>>()
    val processingRecords: LiveData<List<BalanceProcessRecord>> = _processingRecords

    init {
        val database = AppDatabase.getDatabase(application)
        repository = BalanceRepository(database)
        allBalances = repository.getAllBalances()

        // 监听selectedBalanceId的变化，获取相应的Balance对象
        _selectedBalance.addSource(_selectedBalanceId) { id ->
            viewModelScope.launch {
                _selectedBalance.postValue(repository.getBalanceById(id))
            }
        }

        // 监听selectedBalanceId的变化，获取相应的图片列表
        _balanceImages.addSource(_selectedBalanceId) { id ->
            viewModelScope.launch {
                _balanceImages.postValue(repository.getImagesByBalanceId(id).value)
            }
        }
    }

    /**
     * 设置选中的账单ID
     */
    fun selectBalance(id: Long) {
        _selectedBalanceId.value = id
        loadProcessingRecords(id)
    }

    /**
     * 加载处理记录
     */
    private fun loadProcessingRecords(balanceId: Long) {
        viewModelScope.launch {
            _processingRecords.postValue(repository.getProcessRecordsByBalanceId(balanceId))
        }
    }

    /**
     * 创建新账单
     */
    fun createBalance() {
        viewModelScope.launch {
            val balance = Balance().apply {
                status = Balance.STATUS_PENDING
                billDate = LocalDateTime.now()
            }
            val id = repository.saveBalance(balance)
            _selectedBalanceId.postValue(id)
            _operationState.postValue(OperationState.Success("创建成功"))
        }
    }

    /**
     * 保存账单
     */
    fun saveBalance(balance: Balance) {
        viewModelScope.launch {
            _operationState.postValue(OperationState.Loading)
            try {
                repository.saveBalance(balance)
                _operationState.postValue(OperationState.Success("保存成功"))
            } catch (e: Exception) {
                _operationState.postValue(OperationState.Error("保存失败: ${e.message}"))
            }
        }
    }

    /**
     * 删除账单
     */
    fun deleteBalance(balanceId: Long) {
        viewModelScope.launch {
            _operationState.postValue(OperationState.Loading)
            try {
                repository.deleteBalance(balanceId)
                _operationState.postValue(OperationState.Success("删除成功"))
            } catch (e: Exception) {
                _operationState.postValue(OperationState.Error("删除失败: ${e.message}"))
            }
        }
    }

    /**
     * 处理图片
     */
    fun processImage(imageFile: File) {
        viewModelScope.launch {
            _operationState.postValue(OperationState.Loading)
            try {
                val balanceId = _selectedBalanceId.value ?: run {
                    val balance = Balance().apply {
                        status = Balance.STATUS_PENDING
                        billDate = LocalDateTime.now()
                    }
                    repository.saveBalance(balance)
                }
                
                repository.processImage(imageFile, balanceId)
                loadProcessingRecords(balanceId)
                _operationState.postValue(OperationState.Success("处理中"))
            } catch (e: Exception) {
                _operationState.postValue(OperationState.Error("处理失败: ${e.message}"))
            }
        }
    }

    /**
     * 重试处理记录
     */
    fun retryProcessRecord(recordId: Long) {
        viewModelScope.launch {
            _operationState.postValue(OperationState.Loading)
            try {
                // 获取记录并更新状态
                val database = AppDatabase.getDatabase(getApplication())
                val record = database.balanceProcessRecordDao().findById(recordId)
                record?.let {
                    it.status = BalanceProcessRecord.STATUS_PENDING
                    it.retryCount = (it.retryCount ?: 0) + 1
                    repository.saveProcessRecord(it)
                    
                    // 重新加载处理记录
                    val balanceId = it.balanceId ?: return@let
                    loadProcessingRecords(balanceId)
                    _operationState.postValue(OperationState.Success("已提交重试"))
                }
            } catch (e: Exception) {
                _operationState.postValue(OperationState.Error("重试失败: ${e.message}"))
            }
        }
    }

    /**
     * 操作状态密封类
     */
    sealed class OperationState {
        object Loading : OperationState()
        data class Success(val message: String) : OperationState()
        data class Error(val message: String) : OperationState()
    }
} 